package com.shardingsphere.examples.controller;

import com.shardingsphere.examples.entity.Company;
import com.shardingsphere.examples.entity.User;
import com.shardingsphere.examples.service.CompanyService;
import com.shardingsphere.examples.service.UserService;
import com.shardingsphere.examples.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyService companyService;


    @PostMapping("/save")
    @ResponseBody
    public String save(Long count) throws InterruptedException {

        SnowflakeIdWorker userSnowflakeIdWorker = new SnowflakeIdWorker(1,2);
        SnowflakeIdWorker companySnowflakeIdWorker = new SnowflakeIdWorker(3,4);
        Random random = new Random();
        for(int i=0;i<count;i++)
        {
            User user = new User();
            user.setName("用户"+ UUID.randomUUID().toString());
            user.setCreate_time(new Date());
            //生成年龄100随机数
            user.setAge((long)random.nextInt(100)+1);
//            user.setId((long)i);
            user.setId(userSnowflakeIdWorker.nextId());
            userService.save(user);

            Company company = new Company();
//            company.setId((long)i);
            company.setId(companySnowflakeIdWorker.nextId());
            company.setName("公司"+UUID.randomUUID().toString());
            company.setRef_user_id(user.getId());
            company.setUser_age(user.getAge());
            companyService.save(company);
        }
        return "保存成功";
    }



    @PostMapping("/findById")
    @ResponseBody
    public User findById(Long id)
    {
        return userService.findById(id);
    }





    @GetMapping("/findCount")
    @ResponseBody
    public Long findCount()
    {
        return userService.selectCount();
    }


}
